package com.copm.demonstrationsystem.controller.login;

import com.copm.demonstrationsystem.commons.response.ResponseStatus;
import com.copm.demonstrationsystem.pojo.login.User;
import com.copm.demonstrationsystem.service.login.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.jws.soap.SOAPBinding.Use;
import javax.servlet.http.HttpServletRequest;

/**
 * @author chuyunfei
 * @date: 2018/6/11
 * @description:
 */
@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping
    public ResponseStatus login(@RequestParam("count")String count,
            @RequestParam("password") String password,HttpServletRequest request){

        User user = new User(count,password);

        ResponseStatus responseStatus = new ResponseStatus();

        if(user.getCount() == null || user.getCount().isEmpty()
                || user.getPassword() == null || user.getPassword().isEmpty()){
            responseStatus.setStatue(0);
            responseStatus.setMessage("参数出错！");
        }else {
            user = loginService.login(user);
            if(user == null){
                responseStatus.setStatue(0);
                responseStatus.setMessage("没有这个用户！");
            }else {
                responseStatus.setStatue(1);
                responseStatus.setData(user);
                //将登录信息存储到session里面去
                request.getSession().setAttribute("user",user);
            }
        }
        return responseStatus;
    }

    @GetMapping("/status")
    public ResponseStatus getStatus(HttpServletRequest request){

        ResponseStatus responseStatus = new ResponseStatus();

        if(request.getSession().getAttribute("user") == null){
            responseStatus.setStatue(0);
        }else {
            responseStatus.setStatue(1);
        }
        return responseStatus;
    }

    @DeleteMapping("/status")
    public ResponseStatus updateStatus(HttpServletRequest request){

        ResponseStatus responseStatus = new ResponseStatus();

        request.getSession().removeAttribute("user");

        responseStatus.setStatue(1);

        return responseStatus;
    }
}
